﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AsyncCamera.Camera.media;
using Incendios0_1.Camera.wpfdatamanager;
using Emgu.CV;
using AsyncCamera.Camera.Structure;

namespace Incendios0_1.Camera.media.sources
{
    class FileSource: MediaSource
    {
        Capture reader;
        private double counter;

        public FileSource(AbstractCamera camera): base()
        {
            currentState = MediaState.Stop;
            attachCamera(camera);
            counter = 0;
        }

        public void attachCamera(AbstractCamera camera)
        {
            if (currentState == MediaState.Pause || currentState == MediaState.Stop)
            {
                AttachedCamera = camera;
                try
                {
                    reader = new Capture(camera.cameraData.Url);
                }
                catch (Exception e)
                {
                    throw new MediaException(e.Message);
                }
                counter = 0;
            }
        }

        protected override void Tick(object sender, EventArgs e)
        {
            Frame newframe = new Frame();
            newframe.Id = counter;
            newframe.Image = reader.QueryFrame();
            if (newframe.Image == null)
            {
                reader.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_POS_FRAMES,0);
                newframe.Image = reader.QueryFrame();
                AttachedCamera.Height = newframe.Image.Size.Height;
                AttachedCamera.Width = newframe.Image.Size.Width;
            }
            this.Frame = newframe;
            if (counter < double.MaxValue)
                ++counter;
            else
                counter = 0;
        }
    }
}
